import { flux } from './flux'
import HttpUtil from './HttpUtil'

export default class userMgr {
  public wxLoginCode = null;
  public appId = 'wxcc3adba6426ef960';
  public static phone = null


  checkSession() {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: (res) => {
          console.log(res)
          resolve(true)
        },
        fail: (error) => {
          console.log(error)
          reject(error)
        }
      })
    })
  }

  public getUserProfile(event) {
    this.wxLoginCode = null
    return wx.checkSession()
      .then((res) => {
        return this.login(event, true)
      })
      .catch((err) => {
        return this.login(event, false)
      })
  }


  getMiniProgramLoginCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        provider: 'weixin',
        success(loginRes) {
          this.wxLoginCode = loginRes.code
          resolve(this.wxLoginCode)
        },
        fail(res) {
          reject(res)
        }
      })
    })
  }


  public async login(event, expires) {
    // checkSession 过期重新获取code
    if (!expires || !this.wxLoginCode) {
      await this.getMiniProgramLoginCode()
    }
    return HttpUtil.post(
      '/external/gameUser/v1/login',
      {
        encryptedData: event.encryptedData,
        appId: this.appId,
        code: this.wxLoginCode,
        nickName: event.userInfo.nickName,
        avatarUrl: event.userInfo.avatarUrl,
        gender: event.userInfo.gender
      }
    ).then((token) => {
      if (token) {
        return this.getReaderInfo()
      }
      // return flux.reject({})
    })
      .catch((error) => {
        // console.error('重新【token 获取失败】：', error)
        // 解密失败重新获取code
        this.wxLoginCode = null
        this.getMiniProgramLoginCode()
        return flux.reject(error)
      })
  }

  public getReaderInfo() {
    return HttpUtil.get('/external/gameUser/v1/getUserInfo', {}).then((res) => {
      // const { userStore } = useStore()
      // userStore.setUserinfo(res)
      console.log(res)
      return res
    })
  }


}
